var rootPath = getRootPath();
var existRecord = false;

var isRightICreNum = false;
var isRightPCreNum = false;

var oriCreType;
var oriCreNum;
//picName 图片名字  护照不需要这个
var i_creFrontPic = null;
var i_creReversePic = null;

$(function() {
	
	var callbackUrl = getUrlParam("callbackUrl");//getUrlParam 带转义
	if(callbackUrl){
		$(".back").css("display","unset");
		$(".back").click(function(){
			parent.document.location.href = callbackUrl;
		});
	}else{
		$(".back").css("display","none");
	}
	
	//$("#passportForm").hide();
	$(".tip").hide();
	
	$("#i_realNameMsg").hide();
	$("#i_creNumMsg").hide();
	$("#p_realNameMsg").hide();
	$("#p_creNumMsg").hide();
	
	focusById();
	//$("#creType").css("cursor", "pointer");
	
	$.ajax({
		url : rootPath + "/realNameAuth/dr/1/uid",
		method : "GET",
		success : function(data) {
			if('0000' == data.returnCode && data.returnObject != null) {
				existRecord = true;
				var obj = data.returnObject;
				oriCreType = obj.creType;
				oriCreNum = obj.creNum;
				
				$("#creType").find("option[value = '" + oriCreType + "']").prop("selected","selected");
				
				if(oriCreType == "0"){
					
					$("#idCardForm").show();
					$("#passportForm").hide();
					
					$("#i_creNum").val(oriCreNum);
					if(oriCreNum != ""){
						isRightICreNum = true;
					}
					
					$("#i_realName").val(obj.realName);
					if(obj.creFrontPic != '') {
						$("#i_frontImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creFrontPic + "&type=" + 3);
						$("#i_fwSpan").html("");
						i_creFrontPic = obj.creFrontPic;
					 }else{
						 i_creFrontPic = null;
					} 
					if(obj.creReversePic != '') {						
						$("#i_reverseImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creReversePic + "&type=" + 3);
						$("#i_rwSpan").html("");
						i_creReversePic = obj.creReversePic;
					}else{
						i_creReversePic = null;
					}
					showIDButton();
				}else{
					$("#idCardForm").hide();
					$("#passportForm").show();
					
					$("#p_creNum").val(oriCreNum);
					$("#p_realName").val(obj.realName);
					if(obj.creFrontPic != '') {
						$("#p_frontImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creFrontPic + "&type=" + 3);
						$("#p_fwSpan").html("");
					} 
//					if(obj.creReversePic != '') {						
//						$("#p_reverseImg").prop("src",rootPath + "/file/viewimg?fileName=" + obj.creReversePic + "&type=" + 3);
//						$("#p_rwSpan").html("");
//					}
				}
				
				
			}else{
				$("#passportForm").hide();
			}
		},
		error: function (jqXHR, textStatus, errorThrown) {
			layer.alert("error");
		}
	});
	
	$("#i_creNum").focus(function() {
		isRightICreNum = false;
	});
	
	$("#i_creNum").blur(function() {
		checkCreNum(0);
	});
	
	$("#p_creNum").focus(function() {
		isRightPCreNum = false;
	});
	
	$("#p_creNum").blur(function() {
		checkCreNum(1);
	});
 
	$("#i_realName").blur(function() {
		if($.trim($("#i_realName").val()) == '') {
			$("#i_realName").focus();
			showErrMsg("i_realName","请输入真实姓名");
		}else{
			hideMsg("i_realName");
		}
	});
	$("#p_realName").blur(function() {
		if($.trim($("#p_realName").val()) == '') {
			$("#p_realName").focus();
			showErrMsg("p_realName","请输入真实姓名");
		}else{
			hideMsg("p_realName");
		}
	});
	
	$("#i_frontPic").uploadPreview({
		Img : "i_frontImg",
		Width : 100,
		Height : 100
	});
	$("#p_frontPic").uploadPreview({
		Img : "p_frontImg",
		Width : 100,
		Height : 100
	});
	
	$("#i_reversePic").uploadPreview({
		Img : "i_reverseImg",
		Width : 100,
		Height : 100
	});
//	$("#p_reversePic").uploadPreview({
//		Img : "p_reverseImg",
//		Width : 100,
//		Height : 100
//	});
	
	$("#i_frontPic").change(function() {
		if($(this).val() == '') {
			$("#i_frontImg").attr("src","");
			$("#i_fwSpan").removeClass("watermark");
			$("#i_fwSpan").html("请上传证件照(人像面)");
			$(this).parent().children("div[class='tip']").hide();
		}else if($("#creType option:selected").val() == "0" ){
			$("#i_frontPic").showLoading();
			var formData = new FormData();
            formData.append('cardType', 0);
            formData.append('file', this.files[0]);
            validateAuthImg(formData,0);
		}
	});
	$("#p_frontPic").change(function() {
		if($(this).val() == '') {
			$("#p_frontImg").attr("src","");
			$("#p_fwSpan").removeClass("watermark");
			$("#p_fwSpan").html("请上传证件照(人像面)");
			$(this).parent().children("div[class='tip']").hide();
		}
	});
	
	$("#i_reversePic").change(function() {
		if($(this).val() == '') {
			$("#i_reverseImg").attr("src","");
			$("#i_rwSpan").removeClass("watermark");
			$("#i_rwSpan").html("请上传证件照(国徽面)");
			$(this).parent().children("div[class='tip']").hide();
		}else if($("#creType option:selected").val() == "0" ){
			$("#i_reversePic").showLoading();
			var formData = new FormData();
            formData.append('cardType', 1);
            formData.append('file', this.files[0]);
            validateAuthImg(formData,1);
		}
	});
//	$("#p_reversePic").change(function() {
//		if($(this).val() == '') {
//			$("#p_reverseImg").attr("src","");
//			$("#p_rwSpan").removeClass("watermark");
//			$("#p_rwSpan").html("请上传证件照(国徽面)");
//			$(this).parent().children("div[class='tip']").hide();
//		}
//	});
	
	$("#creType").change(function(){
		if($("#creType option:selected").val() == "0" ){
			$("#idCardForm").show();
			$("#passportForm").hide();
		}else{
			$("#idCardForm").hide();
			$("#passportForm").show();
		}
		 
	});
	
	
});

function showErrMsg(id,msg){
	$("#"+id+"Msg").show();
	$("#"+id+"Tip").text(msg);
}

function hideMsg(id) {
	$("#"+id+"Msg").hide();
}

function checkCreNum(idx) {
	var creType = $("#creType option:selected").val();
	var creNum = idx == 0?$("#i_creNum").val():$("#p_creNum").val();
	if($.trim(creNum) == '') {
		if(idx == 0){
			$("#i_creNum").focus();
			showErrMsg("i_creNum","请输入证件号");
			isRightICreNum = false;
			return isRightICreNum;
		}else{
			$("#p_creNum").focus();
			showErrMsg("p_creNum","请输入证件号");
			isRightPCreNum = false;
			return isRightPCreNum;
		}
		 
	}
	
	//检查之前是否存在记录
	if(existRecord && creType == oriCreType && creNum == oriCreNum) {
		if(idx == 0){
			isRightICreNum = true;	
			return isRightICreNum;
		}else{
			isRightPCreNum = true;
			return isRightPCreNum;
		}
	}
	
	var regex;
	if(0 == creType) {
		regex = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
		if(!regex.test(creNum)) {
			$("#i_creNum").focus();
			showErrMsg("i_creNum","身份证输入不合法");
			isRightICreNum = false;
			
		} else {
			vaildateCreNum(creNum);
			isRightICreNum = true;
		}
		return isRightICreNum;
	} else if(1 == creType) {
//		regex = /^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$/;
//		if(!regex.test(creNum)) {
//			$("#p_creNum").focus();
//			showErrMsg("p_creNum","护照输入不合法");
//			isRightPCreNum = false;
//			//return;
//		} else {
			hideMsg("p_creNum");
			isRightPCreNum = true;
//		}
		return isRightPCreNum;
	}
	
}

function focusById(){
	$("#i_realName").focus(function(){
		hideMsg("i_realName");
	});
	$("#i_creNum").focus(function(){
		hideMsg("i_creNum");
	});
	$("#p_realName").focus(function(){
		hideMsg("p_realName");
	});
	$("#p_creNum").focus(function(){
		hideMsg("p_creNum");
	});
}

function validateAuthImg(formData,idx){
	 $.ajax({
         url: rootPath + "/realNameAuth/vaildateAuthImg",
         type: "post",
         data: formData,
         contentType: false,
         processData: false,
         dataType:'json',
         mimeType: "multipart/form-data",
         success: function (data) {
        	 if( 0==idx ){
        		 $("#i_frontPic").hideLoading();
        	 }else{
        		 $("#i_reversePic").hideLoading();
        	 }
        	
        	 if('0000' == data.returnCode && data.returnObject != null) {
        		 
            	var ocr = data.returnObject;
            	if(ocr.ocrCode == "0"){
            		if(ocr.cardType == 0){
            			//人像面
            			i_creFrontPic = ocr.filename;
            			hideMsg("i_realName");
            			hideMsg("i_creNum");
            			if(ocr.ocrName != null && $.trim(ocr.ocrName)!= ''){
            				$("#i_realName").val(ocr.ocrName);
            			}
            			if(ocr.ocrIdCard != null && $.trim(ocr.ocrIdCard)!= ''){
            				$("#i_creNum").val(ocr.ocrIdCard);
                    		vaildateCreNum(ocr.ocrIdCard);
            			}
            		}else{
            			//国徽面
            			i_creReversePic = ocr.filename;
            		}
            	}else if(ocr.cardType == 0){
            		$("#i_realName").val("");
            		$("#i_creNum").val("");
            		isRightICreNum = false;
            		$("#i_creNumMsg").hide();
            		i_creFrontPic = null;
            		layer.alert("证件照（人像面）不规范或者不是身份证人像面！");
            	}else if(ocr.cardType == 1){
            		i_creReversePic= null;
            		layer.alert("证件照（国徽面）不规范或者不是身份证国徽面！");
            	} 
             
            }else{
            	if(0 == idx){
            		i_creFrontPic = null;
            		layer.alert("证件照（人像面）上传失败，请刷新重试！");
            	}else {
            		i_creReversePic= null;
            		layer.alert("证件照（国徽面）上传失败，请刷新重试！");
            	}
            	
            }
        	 showIDButton();
         },
         error: function (e) {
             console.error(e)
         }
     });
}

function showIDButton(){
	$("#idCardBtn").hide();
	$("#idCardBtn").removeAttr("onclick");
	if(isRightICreNum &&( i_creFrontPic !=null && i_creReversePic!=null )){
		$("#idCardBtn").show();
		$("#idCardBtn").attr("onclick","confirmForm(0);");
	}
}
function confirmForm(idx) {
	
	var frontPicId = idx ==0? "#i_frontPic":"#p_frontPic";
	var reversePicId = idx ==0? "#i_reversePic":'';
	var realNameId = idx ==0?"#i_realName":"#p_realName"; 
	var creNumId = idx ==0?"#i_creNum":"#p_creNum"; 

	var frontPicVal = $(frontPicId).val();
	
	var reversePicVal = idx ==0?$(reversePicId).val():'';
	
	if(!existRecord && frontPicVal == '') {
		if(idx == 0){
			layer.alert("请上传身份证证件照的人像面");
		}else{
			layer.alert("请上传证件照");
		}
		
		return;
	}
	
	if(idx == 0 && !existRecord && reversePicVal == '') {
		layer.alert("请上传身份证证件照的国徽面");
		return;
	}
	
	if(frontPicVal != '' && !checkFileExt(frontPicVal)) {
		if(idx == 0){
			layer.alert("人像面证件照格式有误,请选择正确格式的图片");
		}else{
			layer.alert("证件照格式有误,请选择正确格式的图片");
		}
		return;
	}
	
	if(frontPicVal != '' && !lessMaxSize($(frontPicId)[0].files[0])) {
		if(idx == 0){
			layer.alert("人像面证件照太大,请按照提示要求上传图片");
		}else {
			layer.alert("证件照太大,请按照提示要求上传图片");
		}
		return;
	}
	
	if(idx == 0 && reversePicVal != '' && !checkFileExt(reversePicVal)) {
		layer.alert("国徽面证件照格式有误,请选择正确格式的图片");
		return;
	}
	
	if(idx == 0 && reversePicVal != '' && !lessMaxSize($(reversePicId)[0].files[0])) {
		layer.alert("国徽面证件照太大,请按照提示要求上传图片");
		return;
	}
	if($.trim($(realNameId).val()) == '') {
		$(realNameId).focus();
		//showErrMsg(realNameId,"请输入真实姓名");
		layer.alert("请输入真实姓名");
		return;
	}
	if(!checkCreNum(idx)) {
		return;
	}
	//数据长度校验
	if($(realNameId).val().length > 50) {
		$(realNameId).focus();
		//showErrMsg(realNameId, "真实姓名输入过长,请精简");
		layer.alert("真实姓名输入过长,请精简");
		return;
	}
	
	if($(creNumId).val().length > 200) {
		$(creNumId).focus();
			//	showErrMsg(creNumId, "证件号输入过长,请精简");
		layer.alert("证件号输入过长,请精简");
		return;
	}
	
	showLoading();
	var authFormData = {};
	authFormData["creType"] = $("#creType option:selected").val();
	if(idx == 0){
		if(!isRightICreNum){
			layer.alert("证件号码错误或被占用，请重新填写！");
			return;
		}
		if(i_creFrontPic == null || i_creReversePic == null){
			layer.alert("证件图片信息丢失，请刷新重新上传！");
			return;
		}
		authFormData["realName"] = $("#i_realName").val();
		authFormData["creNum"] = $("#i_creNum").val();
		authFormData["creFrontPic"] = i_creFrontPic;
		authFormData["creReversePic"] = i_creReversePic;
		ajaxIdForm(authFormData);
		return;
	}else{
	 $("#passportForm").ajaxSubmit({
		url : rootPath + '/realNameAuth/replaceAuth',
		type: 'POST',
		contentType : 'application/json;charset=UTF-8',
		success : function(data) {
			hideLoading();
			layer.msg("保存成功",{icon:1,time:1000},function() {	
				var callbackUrl = getUrlParam("callbackUrl");//getUrlParam 带转义
				if(callbackUrl){
					parent.document.location.href = callbackUrl;
				}else{
					parent.$("#content").prop("src", "certifyShow.html");
				}
			});
		},
		error: function (jqXHR, textStatus, errorThrown) {
			hideLoading();
			layer.alert("保存失败!");
		}
	});
	}
	return false;
}
function ajaxIdForm(authFormData){
	$.ajax({
		url : rootPath + '/realNameAuth/idCardAuth',
		type: 'POST',
		dataType: 'json',
		contentType : 'application/json;charset=UTF-8',
		data: JSON.stringify(authFormData),
		success:function(res){
			hideLoading();
			if(res.returnCode == "0000"){
				layer.msg("保存成功",{icon:1,time:1000},function() {	
					var callbackUrl = getUrlParam("callbackUrl");//getUrlParam 带转义
					if(callbackUrl){
						parent.document.location.href = callbackUrl;
					}else{
						parent.$("#content").prop("src", "certifyShow.html");
					}
				});
			}else{
				layer.alert(res.returnMessage);
			}
			
		},
		fail:function(){
			console.error("ajaxIdForm error");
		}
	});
}
function vaildateCreNum(i_creNum){
	$.ajax({
		url : rootPath + '/realNameAuth/vaildateCreNum/'+i_creNum,
		dataType: 'json',
		contentType : 'application/json;charset=UTF-8',
		success:function(res){
			if("1004" == res.returnCode){
				if(res.returnObject != null){
            		showErrMsg("i_creNum",res.returnObject);
        			isRightICreNum = false;
            	}else{
            		showErrMsg("i_creNum","身份证已被其他人使用！");
        			isRightICreNum = false;
            	}
			}else{
				isRightICreNum = true; 
			}
			showIDButton();
		},
		fail:function(){
			console.error("ajaxIdForm error");
		}
	});
}
